﻿using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System.Linq;

namespace Fluent.HtmlModel
{
    public class Select<TPage> : HtmlControl<TPage>
        where TPage : WebPageBase
    {
        public Select(TPage page, Finder finder)
            : base(page, finder) { }

        public SelectElement SelectElementObj
        {
            get
            {
                return new SelectElement(this.DriverElement);
            }
        }

        public string SelectedText
        {
            get
            {
                return this.SelectElementObj.SelectedOption.Text;
            }
        }

        public string SelectedValue
        {
            get
            {
                return this.SelectElementObj.SelectedOption.GetAttribute("value");
            }
        }

        public void SelectByValue(string value)
        {
            if (string.IsNullOrEmpty(value) || value == "N/A_-1")
            {
                return;
            }

            this.SelectElementObj.SelectByValue(value);
        }

        public void SelectByText(string text)
        {
            if (string.IsNullOrEmpty(text) || text == "N/A_-1")
            {
                return;
            }

            this.SelectElementObj.SelectByText(text);
        }

        public void SelectByIndex(int index)
        {
            this.SelectByValue(
                this.SelectElementObj
                .Options[index]
                .GetAttribute("value"));
        }

        public bool Contains(string value)
        {
            foreach (var option in this.SelectElementObj.Options)
            {
                if (option.GetAttribute("value") == value)
                {
                    return true;
                }
            }
            return false;
        }
    }
}